import { formatNumber, getOptions, jumpUrl, productList as list } from '@/utils';
import { Button, Card, Col, Flex, Form, InputNumber, Select, Space, Tabs as TabList } from 'antd';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useIntl } from 'umi';

import b_search from '@/assets/b_search.png';
import s_arrow from '@/assets/s_arrow.png';
import search from '@/assets/search.png';
import right from '@/assets/tip_right.png';
import { findByCodeList, handleParams } from '@/services/login';
import { houseValOptions, operateIncomeOptions } from '@/utils/common';

import { useGetToken } from '@/utils/request';
import { useRequest } from 'ahooks';
import AuthButton from '../AuthButton';
import Loading from '../Loading';
import './index.less';
type IPros = {
  onFinish: (value: Center.ProductPrams) => void;
  rightContent?: React.ReactNode;
  value?: Center.ProductPrams;
  needBottomContent?: boolean;
  className?: string;
  onTabChange?: (value: Center.ProductPrams) => void;
  isHome?: boolean;
  topTitle?: any;
  onValuesChange?: (value: any) => void;
};
const Tabs: React.FC<IPros> = ({
  onFinish,
  className,
  rightContent,
  value,
  needBottomContent = true,
  onTabChange,
  topTitle,
  isHome = false,
  onValuesChange,
}) => {
  const { needNumber = false, num, number } = topTitle || {};

  const [loading, setLoading] = useState(true);
  const initVal = {
    loanAmount: 200000,
    loanTerm: '24',
  };
  const { token } = useGetToken();
  const { data } = useRequest(() => handleParams({ code: 'Type_Term_Switch' }));
  const termList = JSON.parse(data?.data?.Type_Term_Switch[0].value || '{}');

  const imgRef = useRef<HTMLImageElement>();

  const { data: selectList } = useRequest(
    () => {
      return findByCodeList({
        code: 'houseType',
      });
    },
    {
      ready: isHome,
    },
  );
  const { houseType } = selectList?.data || {};

  const [activeKey, setActiveKey] = useState(list[0].key);

  useEffect(() => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 200);
  }, [activeKey]);
  const [form] = Form.useForm();
  const input1 = useRef();
  const input2 = useRef();
  const loanAmount = Form.useWatch('loanAmount', form);
  const incoming = Form.useWatch('incoming', form)?.replace('HK$', '');

  const Hkformatter = (value: any) =>
    `${value ? 'HK$' : ''}${formatNumber(value as number, false)}`;

  const Hkparser = (value: any) => value?.replace(/^\H\K\$\s?|(,*)/g, '') as unknown as number;

  const intl = useIntl();
  const isEn = intl.locale == 'en-US';
  const rateList = [10, 20, 30, 40, 48].map((item) => {
    return { value: item, label: `${item}%` };
  });
  useEffect(() => {
    if (value) {
      form.setFieldsValue(value);
    }

    if (value?.productType) {
      setActiveKey(value?.productType as string);
    }
  }, [value, form]);

  const renderForm = useCallback(
    (val: any) => {
      const options = termList[activeKey]?.split(',').map((item: number) => {
        return {
          label: `${intl.formatMessage({ id: 'center.how_month' }, { num: item })}`,
          value: item,
        };
      });
      const amoutLable = 'home.loan_amount';

      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const { needBottomContent, bottomWord } = val || {};

      return (
        <Form
          form={form}
          requiredMark={false}
          className={`tabs_form ${className}`}
          layout="vertical"
          onValuesChange={(values) => {
            if (onValuesChange) {
              onValuesChange(values);
            }
          }}
          initialValues={initVal}
          labelCol={{ span: isHome ? 0 : '' }}
          onFinish={(value: Center.ProductPrams) => {
            if (token) {
              onFinish({ ...value, productType: activeKey });
            } else {
              jumpUrl('/login');
            }
          }}
        >
          {!isHome ? (
            <Flex justify="space-between" gap={10}>
              <Flex
                style={{ flexDirection: 'column', color: '#333', marginBottom: isEn ? 25 : 0 }}
                gap={10}
              >
                <div style={{ fontSize: isEn ? 14 : 18, fontWeight: 700, lineHeight: '20px' }}>
                  <div>
                    {intl.formatMessage(
                      { id: isEn && number <= 1 ? 'home.base1' : 'home.base' },
                      {
                        num,
                        type: intl.formatMessage({ id: list[Number(activeKey) - 1].word }),
                      },
                    )}
                  </div>
                </div>

                <Space align="start" style={{ fontSize: 13 }} size={12}>
                  <img src={right} width={16} height={13} />
                  <div>{intl.formatMessage({ id: 'home.f_tip' })}</div>
                </Space>
                <Space align="start" style={{ fontSize: 13 }} size={12}>
                  <img src={right} width={16} height={13} />
                  <div>{intl.formatMessage({ id: 'home.s_tip' })}</div>
                </Space>
              </Flex>
              <Flex gap={10}>
                <Form.Item
                  label={intl.formatMessage({ id: amoutLable })}
                  rules={[
                    { required: true, message: intl.formatMessage({ id: 'home.loan_amount_msg' }) },
                  ]}
                  name="loanAmount"
                >
                  <InputNumber
                    placeholder={intl.formatMessage({ id: amoutLable })}
                    variant="borderless"
                    formatter={Hkformatter}
                    parser={Hkparser}
                    controls={false}
                    style={{
                      background: '#fff',
                      borderRadius: 8,
                      width: 220,
                      height: 52,
                      lineHeight: '52px',
                    }}
                  />
                </Form.Item>
                <Form.Item
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'home.input_pay_period' }),
                    },
                  ]}
                  name="loanTerm"
                  label={intl.formatMessage({ id: 'home.loan_term' })}
                >
                  <Select
                    suffixIcon={<img src={s_arrow} width={14} style={{ marginRight: 7 }} />}
                    options={options}
                    style={{ background: '#fff', borderRadius: 8, width: 300, height: 52 }}
                    placeholder={intl.formatMessage({ id: 'home.loan_term' })}
                  />
                </Form.Item>
                <Form.Item>
                  <Button
                    onMouseOver={() => {
                      if (imgRef.current) {
                        imgRef.current.src = search;
                      }
                    }}
                    onMouseOut={() => {
                      if (imgRef.current) {
                        imgRef.current.src = b_search;
                      }
                    }}
                    className="tabs_btn"
                    htmlType="submit"
                    style={{ border: 'none', marginTop: isHome ? 0 : 30 }}
                    icon={<img ref={imgRef as any} src={b_search} width={20} />}
                  >
                    <div>{intl.formatMessage({ id: 'home.compare_now' })}</div>
                  </Button>
                </Form.Item>
              </Flex>
            </Flex>
          ) : loading ? (
            <Flex style={{ height: 76 }} justify="center">
              <Form.Item>
                <Loading style={{ width: 35, borderWidth: 3.5, height: 35 }} />
              </Form.Item>
            </Flex>
          ) : (
            <Flex gap={10} align="center">
              <Form.Item
                label={intl.formatMessage({
                  id: amoutLable,
                })}
                rules={[
                  { required: true, message: intl.formatMessage({ id: 'home.loan_amount_msg' }) },
                ]}
                className="tab_inputNumber"
                name="loanAmount"
              >
                <InputNumber
                  formatter={Hkformatter}
                  parser={Hkparser}
                  controls={false}
                  ref={input1 as any}
                  onMouseOut={() => {
                    (input1.current as any)?.blur();
                  }}
                  onClick={() => {
                    (input1.current as any)?.focus();
                  }}
                  className={`${loanAmount ? 'tab_postion' : null}`}
                  addonBefore={
                    <div
                      onClick={() => {
                        (input1.current as any)?.focus();
                      }}
                    >
                      {intl.formatMessage({ id: amoutLable })}
                    </div>
                  }
                  style={{
                    background: '#fff',
                    borderRadius: 8,
                    width: 220,
                    height: 52,
                    lineHeight: '52px',
                  }}
                />
              </Form.Item>
              <Form.Item
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'home.input_pay_period' }),
                  },
                ]}
                name="loanTerm"
                label={intl.formatMessage({ id: 'home.pay_period' })}
              >
                <Select
                  suffixIcon={<img src={s_arrow} width={14} style={{ marginRight: 7 }} />}
                  labelRender={({ label }) => {
                    return (
                      <>
                        <Col style={{ color: '#999999', fontSize: 12, marginBottom: -11 }}>
                          {intl.formatMessage({ id: 'home.pay_period' })}
                        </Col>
                        <Col style={{ color: '#333', fontSize: 16 }}> {label}</Col>
                      </>
                    );
                  }}
                  options={options}
                  style={{ background: '#fff', borderRadius: 8, width: 300, height: 52 }}
                  placeholder={intl.formatMessage({ id: 'home.pay_period' })}
                />
              </Form.Item>
              {['1', '2', '3', '5'].includes(activeKey) ? (
                <>
                  {activeKey == '3' ? (
                    <Form.Item
                      rules={[
                        {
                          required: true,
                          message: intl.formatMessage({ id: 'home.input_house_vals' }),
                        },
                      ]}
                      name="house"
                      label={intl.formatMessage({ id: 'home.house_vals' })}
                    >
                      <Select
                        suffixIcon={<img src={s_arrow} width={14} style={{ marginRight: 7 }} />}
                        labelRender={({ label }) => {
                          return (
                            <>
                              <Col style={{ color: '#999999', fontSize: 12, marginBottom: -11 }}>
                                {intl.formatMessage({ id: 'home.house_vals' })}
                              </Col>
                              <Col style={{ color: '#333', fontSize: 16 }}> {label}</Col>
                            </>
                          );
                        }}
                        options={houseValOptions}
                        style={{ background: '#fff', borderRadius: 8, width: 300, height: 52 }}
                        placeholder={intl.formatMessage({ id: 'home.house_vals' })}
                      />
                    </Form.Item>
                  ) : (
                    <Form.Item
                      rules={[
                        {
                          required: true,
                          message: intl.formatMessage({ id: 'home.input_max_rate' }),
                        },
                      ]}
                      name="rate"
                      label={intl.formatMessage({ id: 'home.max_rate' })}
                    >
                      <Select
                        suffixIcon={<img src={s_arrow} width={14} style={{ marginRight: 7 }} />}
                        labelRender={({ label }) => {
                          return (
                            <>
                              <Col style={{ color: '#999999', fontSize: 12, marginBottom: -11 }}>
                                {intl.formatMessage({ id: 'home.max_rate' })}
                              </Col>
                              <Col style={{ color: '#333', fontSize: 16 }}> {label}</Col>
                            </>
                          );
                        }}
                        options={rateList}
                        style={{ background: '#fff', borderRadius: 8, width: 300, height: 52 }}
                        placeholder={intl.formatMessage({ id: 'home.max_rate' })}
                      />
                    </Form.Item>
                  )}
                  {activeKey == '5' ? (
                    <Form.Item
                      rules={[
                        {
                          required: true,
                          message: intl.formatMessage({ id: 'home.input_operating_income' }),
                        },
                      ]}
                      name="operate"
                      label={intl.formatMessage({ id: 'home.operating_income' })}
                    >
                      <Select
                        suffixIcon={<img src={s_arrow} width={14} style={{ marginRight: 7 }} />}
                        labelRender={({ label }) => {
                          return (
                            <>
                              <Col style={{ color: '#999999', fontSize: 12, marginBottom: -11 }}>
                                {intl.formatMessage({ id: 'home.operating_income' })}
                              </Col>
                              <Col style={{ color: '#333', fontSize: 16 }}> {label}</Col>
                            </>
                          );
                        }}
                        options={operateIncomeOptions}
                        style={{ background: '#fff', borderRadius: 8, width: 300, height: 52 }}
                        placeholder={intl.formatMessage({ id: 'home.operating_income' })}
                      />
                    </Form.Item>
                  ) : (
                    <Form.Item
                      rules={[{ required: true }]}
                      name="incoming"
                      label={intl.formatMessage({ id: 'home.month_income' })}
                      className="tab_inputNumber"
                    >
                      <div
                        onClick={() => {
                          (input2.current as any)?.focus();
                        }}
                      >
                        <InputNumber
                          ref={input2 as any}
                          // onMouseOut={() => {
                          //   (input2.current as any)?.blur();
                          // }}
                          className={`${incoming ? 'tab_postion' : null}`}
                          formatter={Hkformatter}
                          parser={Hkparser}
                          controls={false}
                          addonBefore={
                            <div
                              onClick={() => {
                                (input2.current as any)?.focus();
                              }}
                            >
                              {intl.formatMessage({ id: 'home.month_income' })}
                            </div>
                          }
                          style={{
                            background: '#fff',
                            borderRadius: 8,
                            width: 220,
                            height: 52,
                            lineHeight: '52px',
                          }}
                        />
                      </div>
                    </Form.Item>
                  )}
                </>
              ) : (
                <>
                  <Form.Item
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({ id: 'home.input_house_vals' }),
                      },
                    ]}
                    name="house"
                    label={intl.formatMessage({ id: 'home.house_vals' })}
                  >
                    <Select
                      suffixIcon={<img src={s_arrow} width={14} style={{ marginRight: 7 }} />}
                      labelRender={({ label }) => {
                        return (
                          <>
                            <Col style={{ color: '#999999', fontSize: 12, marginBottom: -11 }}>
                              {intl.formatMessage({ id: 'home.house_vals' })}
                            </Col>
                            <Col style={{ color: '#333', fontSize: 16 }}> {label}</Col>
                          </>
                        );
                      }}
                      options={houseValOptions}
                      style={{ background: '#fff', borderRadius: 8, width: 300, height: 52 }}
                      placeholder={intl.formatMessage({ id: 'home.house_vals' })}
                    />
                  </Form.Item>
                  <Form.Item
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({ id: 'home.input_house_type' }),
                      },
                    ]}
                    name="house_type"
                    label={intl.formatMessage({ id: 'home.house_type' })}
                  >
                    <Select
                      suffixIcon={<img src={s_arrow} width={14} style={{ marginRight: 7 }} />}
                      labelRender={({ label }) => {
                        return (
                          <>
                            <Col style={{ color: '#999999', fontSize: 12, marginBottom: -11 }}>
                              {intl.formatMessage({ id: 'home.house_type' })}
                            </Col>
                            <Col style={{ color: '#333', fontSize: 16 }}> {label}</Col>
                          </>
                        );
                      }}
                      options={getOptions(houseType)}
                      style={{ background: '#fff', borderRadius: 8, width: 300, height: 52 }}
                      placeholder={intl.formatMessage({ id: 'home.house_type' })}
                    />
                  </Form.Item>
                </>
              )}
              <Form.Item>
                <AuthButton
                  onMouseOver={() => {
                    if (imgRef.current) {
                      imgRef.current.src = search;
                    }
                  }}
                  onMouseOut={() => {
                    if (imgRef.current) {
                      imgRef.current.src = b_search;
                    }
                  }}
                  className="tabs_btn"
                  htmlType="submit"
                  style={{ border: 'none', marginTop: isHome ? 0 : 26 }}
                  icon={<img ref={imgRef as any} src={b_search} width={20} />}
                >
                  <div>{intl.formatMessage({ id: 'home.compare_now' })}</div>
                </AuthButton>
              </Form.Item>
            </Flex>
          )}

          {/* {needBottomContent ? (
            <div style={{ padding: '0 8px' }}>
              <div
                style={{
                  backgroundColor: '#ECF3FE',
                  padding: '9.5px 12px',
                  fontSize: 14,
                  color: '#0270DF',
                  borderRadius: 4,
                  fontWeight: 400,
                  display: 'flex',
                }}
              >
                <img src={trumpet} width={20} height={22} style={{ marginRight: 5 }} />

                <div>{intl.formatMessage({ id: bottomWord })}</div>
              </div>
            </div>
          ) : null} */}
        </Form>
      );
    },

    // eslint-disable-next-line react-hooks/exhaustive-deps
    [activeKey, form, intl, onFinish, termList, houseType, className, num, needNumber, list],
  );
  return (
    <div style={{ marginTop: 25, position: 'relative', zIndex: 1 }}>
      <Card
        styles={{
          body: {
            padding: isHome ? '24px 50px 0' : '24px 50px 3px',
            boxShadow: '0px 4px 6px 0px #0000001A',
          },
        }}
      >
        <div className={`tabs ${isEn ? 'en_tabs' : ''}`}>
          <TabList
            tabBarExtraContent={{ right: rightContent }}
            onChange={(activeKey) => {
              setActiveKey(activeKey);
              form.resetFields();
              if (onTabChange) {
                onTabChange({
                  productType: activeKey,
                  ...initVal,
                });
              }
            }}
            activeKey={activeKey}
            tabBarGutter={20}
            items={list.map((item) => {
              const { word, icon, key, bottomWord } = item;
              return {
                key,
                label: (
                  <Flex align="center" gap={8}>
                    <img
                      src={activeKey == key ? require(`@/assets/top_icon${activeKey}.png`) : icon}
                      width={20}
                    />
                    <div className="tabs_word"> {intl.formatMessage({ id: word })}</div>
                  </Flex>
                ),
                children: <>{renderForm({ bottomWord, needBottomContent })}</>,
              };
            })}
            destroyInactiveTabPane
          />
        </div>
      </Card>
    </div>
  );
};

export default Tabs;
